package com.andy.basics;

import java.util.List;

import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

public abstract class Service<T extends Entity> extends Component {

	private GenericDao genericDao;

	protected DataModel dataModel;

	protected List<T> models;

	public List<T> getModels() {
		if (this.models == null) {
			this.models = this.findAll();
		}
		return this.models;
	}

	public void setModels(final List<T> models) {
		this.models = models;
	}

	private T model;

	private boolean editing;

	@Autowired
	private Utils utils;

	public void remove(final T t) {
		this.getDao().remove(t);
		this.dataModel = null;
		this.models = null;
	}

	@Transactional
	public void save(final T t) {
		this.getDao().persist(t);
		this.dataModel = null;
		this.models = null;
		this.model = null;
	}

	@Transactional
	public void update(final T t) {
		this.getDao().update(t);
		this.dataModel = null;
		this.model = null;
		this.models = null;
		this.dataModel = null;
		this.editing = false;
	}

	public List<T> findAll() {
		return this.getDao().findAll();
	}

	public List<T> find(final String condition) {
		return this.getDao().find(condition);
	}

	public List<T> getAll() {
		return this.findAll();
	}

	public void setDataModel(final DataModel dataModel) {
		this.dataModel = dataModel;
	}

	public DataModel getDataModel() {
		if (this.dataModel == null) {
			this.dataModel = new ListDataModel(this.getDao().getAll());
		}
		return this.dataModel;
	}

	public void setModel(final T model) {
		this.model = model;
	}

	public T getModel() {
		return this.model;
	}

	public void setEditing(final boolean editing) {
		this.editing = editing;
	}

	public boolean isEditing() {
		return this.editing;
	}

	public abstract Dao<T> getDao();

	public void setUtils(final Utils utils) {
		this.utils = utils;
	}

	public Utils getUtils() {
		return this.utils;
	}

	@Autowired
	public void setGenericDao(final GenericDao genericDao) {
		this.genericDao = genericDao;
	}

	public GenericDao getGenericDao() {
		return this.genericDao;
	}

	public void reload() {

	}

}
